package com.yh.workbill.ui.search;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.yh.workbill.R;
import com.yh.workbill.adapter.HomeWorkBillAdapter;
import com.yh.workbill.adapter.TimeDropDownAdapter;
import com.yh.workbill.base.BaseActivity;
import com.yh.workbill.databinding.ActivitySearchBinding;
import com.yh.workbill.databinding.LayoutHeadBinding;
import com.yh.workbill.event.EditWorkBillEvent;
import com.yh.workbill.model.WorkBill;
import com.yh.workbill.ui.editworkbill.EditWorkBillActivity;
import com.yh.workbill.ui.home.HomeViewModel;
import com.yh.workbill.ui.search.mvp.Search_Presenter;
import com.yh.workbill.ui.search.mvp.Search_View;
import com.yh.workbill.utils.Utils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

public class SearchActivity extends BaseActivity implements Search_View {
    private ActivitySearchBinding binding;
    private HomeWorkBillAdapter adapter;
    private List<WorkBill> workBills = new ArrayList<>();
    private LayoutHeadBinding layoutHead;
    private HomeViewModel viewModel;
    private Search_Presenter presenter;
    private TimeDropDownAdapter yearAdapter, monthAdapter;
    private List<String> yearList, monthList;
    private boolean isYear, isMonth;
    private int yearIndex = 0, monthIndex = 0;
    private int pageindex = 1, pagenumber = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_search);
        layoutHead = binding.layoutHead;
    }

    @Override
    public void initJetPack(@Nullable Bundle savedInstanceState) {
        presenter = new Search_Presenter(this);
        viewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        binding.setLifecycleOwner(this);
        this.getLifecycle().addObserver(presenter);
    }

    @Override
    public void initObserve(@Nullable Bundle savedInstanceState) {
        this.getLifecycle().addObserver(presenter);
        binding.setLifecycleOwner(this);
        viewModel.getWorkBilldata().observe(this, data -> {
//            for (WorkBill bean : data) {
//                Log.e("TAG", "观察数据是:" + bean.getCompany_name() + " " + bean.getWork_unit() + "\n");
//            }
            adapter.setWorkBills(data);
        });
    }

    @Override
    public void initBaseSetting(@Nullable Bundle savedInstanceState) {
        layoutHead.setTitle("搜索");

        adapter = new HomeWorkBillAdapter(workBills);
        binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        binding.recyclerView.setAdapter(adapter);

        initDropDown();
        yearAdapter.setOnItemClick((data, position) -> {
            binding.rvYear.setVisibility(View.GONE);
            binding.tvYear.setText(data);
            binding.tvYear.setTextColor(getResources().getColor(R.color.dialog_text));
            binding.ivYear.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
            yearAdapter.setCheckItem(position);
            yearIndex = position;
            pageindex = 1;
            search(true, false);
        });

        monthAdapter.setOnItemClick((data, position) -> {
            binding.rvMonth.setVisibility(View.GONE);
            binding.tvMonth.setText(data);
            binding.tvMonth.setTextColor(getResources().getColor(R.color.dialog_text));
            binding.ivMonth.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
            monthAdapter.setCheckItem(monthIndex);
            monthIndex = position;
            pageindex = 1;
            search(true, false);
        });

    }

    @Override
    public void initClick(@Nullable Bundle savedInstanceState) {
        layoutHead.llBlack.setOnClickListener(v -> finish());
        binding.llYear.setOnClickListener(v -> {
            if (binding.rvMonth.getVisibility() == View.VISIBLE) {
                binding.rvMonth.setVisibility(View.GONE);
                binding.tvMonth.setTextColor(getResources().getColor(R.color.dialog_text));
                binding.ivMonth.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
                isMonth = false;
            }

            if (!isYear) {
                binding.rvYear.setVisibility(View.VISIBLE);
                binding.rvYear.setAdapter(yearAdapter);
                yearAdapter.setList(yearList);
                yearAdapter.setCheckItem(yearIndex);
                binding.tvYear.setTextColor(getResources().getColor(R.color.colorAccent));
                binding.ivYear.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_selected_icon));
                isYear = true;
            } else {
                binding.rvYear.setVisibility(View.GONE);
                binding.tvYear.setTextColor(getResources().getColor(R.color.dialog_text));
                binding.ivYear.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
                isYear = false;
            }

        });
        binding.llMonth.setOnClickListener(v -> {
            if (binding.rvYear.getVisibility() == View.VISIBLE) {
                binding.rvYear.setVisibility(View.GONE);
                binding.tvYear.setTextColor(getResources().getColor(R.color.dialog_text));
                binding.ivYear.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
                isYear = false;
            }

            if (!isMonth) {
                binding.rvMonth.setVisibility(View.VISIBLE);
                binding.rvMonth.setAdapter(monthAdapter);
                monthAdapter.setList(monthList);
                monthAdapter.setCheckItem(monthIndex);
                binding.tvMonth.setTextColor(getResources().getColor(R.color.colorAccent));
                binding.ivMonth.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_selected_icon));
                isMonth = true;
            } else {
                binding.rvMonth.setVisibility(View.GONE);
                binding.tvMonth.setTextColor(getResources().getColor(R.color.dialog_text));
                binding.ivMonth.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
                isMonth = false;
            }
        });
        binding.tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pageindex = 1;
                search(true, false);
                if (binding.rvYear.getVisibility() == View.VISIBLE) {
                    binding.rvYear.setVisibility(View.GONE);
                    binding.tvYear.setTextColor(getResources().getColor(R.color.dialog_text));
                    binding.ivYear.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
                    isYear = false;
                }
                if (binding.rvMonth.getVisibility() == View.VISIBLE) {
                    binding.rvMonth.setVisibility(View.GONE);
                    binding.tvMonth.setTextColor(getResources().getColor(R.color.dialog_text));
                    binding.ivMonth.setBackground(getResources().getDrawable(R.mipmap.ic_drop_down_unselected_icon));
                    isMonth = false;
                }

            }
        });

        binding.etCompany.addTextChangedListener(textWatcher);
        binding.ivClear.setOnClickListener(v -> {
            binding.etCompany.setText("");
            binding.ivClear.setVisibility(View.GONE);
        });
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (count > 0) {
                binding.ivClear.setVisibility(View.VISIBLE);
            } else if (count <= 0) {
                binding.ivClear.setVisibility(View.GONE);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Override
    public void initDefaultMethod(@Nullable Bundle savedInstanceState) {
        binding.refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageindex = 1;
                search(true, false);
            }
        });

        binding.refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                search(false, true);
            }
        });

        adapter.setmOnItemClick((workBill, position) -> {
            Intent i = new Intent(this, EditWorkBillActivity.class);
            i.putExtra("workbill", workBill);
            startActivity(i);
        });
    }

    private void initDropDown() {
        binding.rvYear.setLayoutManager(new LinearLayoutManager(this));
        binding.rvMonth.setLayoutManager(new LinearLayoutManager(this));

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String currentTime = df.format(new Date());
        String[] split = currentTime.split("-");
        yearList = new ArrayList<>();
        int endYear = Integer.valueOf(split[0]);
        for (int i = 2017; i <= endYear; i++) {
            yearList.add(i + "年");
        }
        Collections.reverse(yearList);

        yearAdapter = new TimeDropDownAdapter(this, yearList);

        monthList = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            if (i == 1) {
                monthList.add("全部");
            }
            monthList.add(i + "月");
        }
        monthAdapter = new TimeDropDownAdapter(this, monthList);

        binding.tvYear.setText(yearList.get(0));
        binding.tvMonth.setText(monthList.get(0));
        yearAdapter.setCheckItem(yearIndex);
        monthAdapter.setCheckItem(monthIndex);
    }

    @Override
    public void getData(List<WorkBill> data) {
        pageindex++;
    }

    @Override
    public void fail(String msg) {
        viewModel.addNoworkBilldata();
        Utils.ShowToas(this, msg);
        binding.refreshLayout.finishRefresh();
        binding.refreshLayout.finishLoadMore();
    }

    @Override
    public void refresh() {
        binding.refreshLayout.finishRefresh();
    }

    @Override
    public void loadMore() {
        binding.refreshLayout.finishLoadMore();
    }

    @Override
    public void showTasot(String message) {
        Utils.ShowToas(this, message);
    }

    @Override
    public void showDialog(String content, boolean isCancelable) {
        showLoaddingDialog(content, isCancelable);
    }

    @Override
    public void hideDialog() {
        hideLoaddingDialog();
    }

    private void search(boolean isRefresh, boolean isLoadmore) {
        String companyName = binding.etCompany.getText().toString().trim();
        String temp_year = binding.tvYear.getText().toString();
        String year = temp_year.substring(0, temp_year.length() - 1);
        String temp_month = binding.tvMonth.getText().toString();
        String month;
        if (temp_month.equals("全部")) {
            month = "0";
        } else {
            month = temp_month.substring(0, temp_month.length() - 1);
        }
        presenter.getSearch(viewModel, isRefresh, isLoadmore, companyName, year, month, pageindex, pagenumber);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdataWorkBillEvent(EditWorkBillEvent event) {
        WorkBill workBill = event.getWorkBill();
        if (workBill != null) {
            List<WorkBill> value = viewModel.getWorkBilldata().getValue();
            for (WorkBill bean : value) {
                if (bean.getUuid().equals(workBill.getUuid())) {
                    bean.setWork_time(workBill.getWork_time());
                    bean.setWork_unit(workBill.getWork_unit());
                    bean.setWork_content(workBill.getWork_content());
                    bean.setWork_car_number(workBill.getWork_car_number());
                    bean.setWork_device(workBill.getWork_device());
                    bean.setWork_use_time(workBill.getWork_use_time());
                    bean.setWork_time_price(workBill.getWork_time_price());
                    double money = workBill.getWork_time_price() / 8 * workBill.getWork_use_time();
                    bean.setWork_money(money);
                    bean.setCompany_uuid(workBill.getCompany_uuid());
                    bean.setCompany_name(workBill.getCompany_name());
                    bean.setCheck(workBill.isCheck());
                    break;
                }
            }
            viewModel.update();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDelWorkBillEvent(EditWorkBillEvent event) {
        String uuid = event.getUuid();
        if (!TextUtils.isEmpty(uuid)) {
            List<WorkBill> value = viewModel.getWorkBilldata().getValue();
            Iterator<WorkBill> it = value.iterator();
            while (it.hasNext()) {
                WorkBill next = it.next();
                if (next.getUuid().equals(uuid)) {
                    it.remove();
                }
            }
            viewModel.update();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (textWatcher != null) {
            textWatcher = null;
        }
    }
}
